package caro.client.controller;

import caro.client.gui.Login;
import caro.client.gui.Messages;
import caro.client.gui.ServerConnection;
import java.awt.Cursor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;

/**
 * Class ServerConnectionCtr
 * @author Thanh Nhan
 * @Since Aug 28, 2011
 * @Version 1.0
 */
public class ServerConnectionCtr {
    private ServerConnection serverConnectionUI = null;
    public ServerConnectionCtr(ServerConnection serverConnectionUI){
        this.serverConnectionUI = serverConnectionUI;
        this.serverConnectionUI.addConnectListener(new ServerConnectionListener());
        this.serverConnectionUI.addExitListener(new ExitListener());
    }
    class ExitListener implements ActionListener{

        @Override
        public void actionPerformed(ActionEvent e) {
            System.exit(0);
        }
        
    }
    class ServerConnectionListener implements ActionListener{

        @Override
        public void actionPerformed(ActionEvent e) {
            final String ip = serverConnectionUI.getServerIp();
            final int port = Integer.parseInt(serverConnectionUI.getServerPort());
            
            final Waiting w = new Waiting(serverConnectionUI);
            w.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
            new Thread(){
                @Override
                public void run(){
                    w.setVisible(true);
                }
            }.start();
            new Thread(){
                @Override
                public void run(){
                    Socket s = null;
                    try {
                        s = new Socket(ip, port);
                        Login login = new Login(s, serverConnectionUI);
                        LoginController loginCtr = new LoginController(login);
                        login.setVisible(true);
                        w.dispose();
                        serverConnectionUI.hide();
                    } catch (Exception ex) {
                        JOptionPane.showMessageDialog(serverConnectionUI, Messages.getString("errorConnection", ip, port)
                                , Messages.getString("errorTitle"), JOptionPane.ERROR_MESSAGE);
                        
                    }
                    w.dispose();
                }
            }.start();
            
        }
        
    }
}
